package cn.fsd.service.impl;

import cn.fsd.domain.Commodity;
import cn.fsd.domain.Storeroom;
import cn.fsd.mapper.CommodityClassMapper;
import cn.fsd.mapper.CommodityMapper;
import cn.fsd.mapper.StoreroomMapper;
import cn.fsd.mapper.Storeroom_commodityMapper;
import cn.fsd.mapper.SuppliersMapper;
import cn.fsd.query.delivery.CommodityClassQuery;
import cn.fsd.query.delivery.CommodityQuery;
import cn.fsd.service.CommodityService;
import cn.fsd.util.CacheConstant;
import cn.fsd.vo.CommodityBean;
import cn.fsd.vo.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@CacheConfig(cacheNames = CacheConstant.COMMODITY_CACHE_NAME)
public class CommodityServiceImpl implements CommodityService {

  @Autowired
  CommodityMapper commodityMapper;
  @Autowired
  CommodityClassMapper classMapper;
  @Autowired
  SuppliersMapper supplierMapper;
  @Resource
  StoreroomMapper storeroomMapper;
  @Resource
  Storeroom_commodityMapper storeroomCommodityMapper;

  @CacheEvict(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX + "all'")
  @Override
  public String addCommodity(Commodity commodity) {
    String id = UUID.randomUUID().toString();
    commodity.setCommodity_id(id);
    commodityMapper.insert(commodity);
    //添加商品还需要给每个库房都加上这个商品的库存
    List<Storeroom> storeroomList = storeroomMapper.selectAll();
    storeroomCommodityMapper.addCommodityInAllStoreroom(commodity.getCommodity_id(),storeroomList);
    return id;
  }

  @Caching(evict = {@CacheEvict(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX + "' + #commodityId"),
      @CacheEvict(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX + "all'"),
      @CacheEvict(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX + "_the_' + #commodityId")})
  @Override
  public void delCommodity(String commodityId) {
    commodityMapper.deleteByPrimaryKey(commodityId);
  }

  @Cacheable(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX
      + "' + #commodityId", unless = "#result == null")
  @Override
  public CommodityBean findCommodityById(String commodityId) {
    return transferCommodity(commodityMapper.selectByPrimaryKey(commodityId));
  }

  @Override
  public Commodity findCommodityByName(String commodityName) {
    return commodityMapper.findCommodityByName(commodityName);
  }

  @Cacheable(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX
      + "all'", unless = "#result.size() == 0")
  @Override
  public List<Commodity> findAllCommodity() {
    return commodityMapper.selectAll().parallelStream().map(this::transferCommodity).collect(
        Collectors.toList());
  }

  @Override
  public List<Commodity> findCommodityPatch(List<String> ids) {
    if(ids==null||ids.isEmpty())return new ArrayList<>();
    List<Commodity> result = new ArrayList<>();
    ids.forEach(item->{
      Commodity commodity = commodityMapper.selectByPrimaryKey(item);
      if(commodity!=null){
        result.add(commodity);
      }
    });
    return result;
  }

  @Override
  public List<Commodity> findCommodityByClass(CommodityClassQuery query) {
    return commodityMapper.getCommodityByClass(query).parallelStream().map(this::transferCommodity).collect(
        Collectors.toList());
  }

  @Override
  public List<Commodity> findCommodityByCode(String code) {
    return commodityMapper.selectByCode(code);
  }

  @Transactional(readOnly = true)
  @Override
  public PageBean<Commodity> findByPage(CommodityQuery query) {
    //构建结果对象
    PageBean<Commodity> pageBean = new PageBean<>();

    //开启分页
    PageHelper.startPage(query.getPageNow(), query.getPageSize());

//        分页查询得到当页的集合
    List<Commodity> studentList = commodityMapper.findByPage(query);

//        创建分页实体pageInfo
    PageInfo<Commodity> pageInfo = new PageInfo<>(studentList);

    pageInfo.setList(
        pageInfo.getList().parallelStream().map(this::transferCommodity).collect(Collectors.toList()));

    pageBean.setTotalRows(pageInfo.getTotal());
    pageBean.setTotalPages(pageInfo.getPages());
    pageBean.setRowData(pageInfo.getList());

    System.out.println(query);
    System.out.println(pageBean);
    return pageBean;
  }

  @Caching(evict = {@CacheEvict(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX + "all'"),
      @CacheEvict(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX + "' + #commodity.commodity_id"),
      @CacheEvict(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX + "_the_' + #commodity.commodity_id")})
  @Override
  public void updateCommodity(Commodity commodity) {
    commodityMapper.updateByPrimaryKey(commodity);
  }

  @Cacheable(key = "'" + CacheConstant.COMMODITY_CACHE_KEY_PREFIX
      + "_the_' + #id", unless = "#result == null")
  @Override
  public Commodity getTheCommodity(String id) {
    return commodityMapper.selectByPrimaryKey(id);
  }

  @Override
  public List<Commodity> getCommoditiesByClass(String firstClass, String secondClass,
      String commodityName) {
//    List<CommodityClass> commodityClasses = classMapper.getByNameVague(className);
    return commodityMapper.getCommodityByClassCommodityName(firstClass,secondClass,commodityName);
  }

  public CommodityBean transferCommodity(Commodity commodity) {
    if (commodity == null) {
      return null;
    }
    CommodityBean bean = new CommodityBean(commodity);
    bean.setFirstClassName(classMapper.selectByPrimaryKey(bean.getFirst_class()) != null
        ? classMapper.selectByPrimaryKey(bean.getFirst_class()).getName() : "");
    bean.setSecondClassName(classMapper.selectByPrimaryKey(bean.getSecond_class()) != null
        ? classMapper.selectByPrimaryKey(bean.getSecond_class()).getName() : "");
    bean.setSupplierName(supplierMapper.selectByPrimaryKey(bean.getSupplier()) != null
        ? supplierMapper.selectByPrimaryKey(bean.getSupplier()).getSupplier_name() : "");
    return bean;
  }
}
